<template>
  <div ref="mapRef" :style="{ width: `${width}vw`, height: `${height}vw` }"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const props = defineProps<{
  width?: number
  height?: number
  jsonPath?: string // 地图json路径
  addressJX?: string // 地图名称英文简写
  color?: string
}>()

const mapRef = ref(null)
const mapEcharts = ref<any>(null)

function handleResize() {
  mapEcharts.value.resize({ width: 'auto', height: 'auto' })
}

onMounted(() => {
  mapEcharts.value = echarts.init(mapRef.value)
  mapEcharts.value.showLoading()
  fetch(props.jsonPath ?? '').then((res) => {
    if (res.ok) {
      res.json().then((geoJson) => {
        mapEcharts.value.hideLoading()
        echarts.registerMap(props.addressJX ?? 'QDN', geoJson)
        mapEcharts.value.setOption({
          series: [
            {
              type: 'map',
              map: props.addressJX,
              label: {
                show: true,
                color: 'white',
                fontSize: '8px'
              },
              itemStyle: {
                areaColor: props.color,
                borderColor: 'black'
              },
              left: 5,
              top: 5,
              right: 5,
              bottom: 5
            }
          ]
        })
      })
    }
  })
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})
</script>
